package com.net.common.enums.gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.net.common.enums.base.StringEnum;

/**
 * @author  on 2017/6/14.
 * 处理StringEnum的gson逻辑
 */
public class StringEnumAdapter<E extends Enum<E> & StringEnum<E>> extends TypeAdapter<E> {
    public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
        @Override
        @SuppressWarnings({"unchecked", "rawtypes"})
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
            Class<? super T> rawType = typeToken.getRawType();
            if (!StringEnum.class.isAssignableFrom(rawType)) {
                return null;
            }

            return new StringEnumAdapter(rawType);
        }
    };

    private final Map<String, E> valueToConstant = new HashMap<>();
    private final Map<E, String> constantToValue = new HashMap<>();

    public StringEnumAdapter(Class<E> classOfT) {
        for (E constant : classOfT.getEnumConstants()) {
            String value = constant.getValue();
            valueToConstant.put(value, constant);
            constantToValue.put(constant, value);
        }
    }

    @Override
    public E read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        return valueToConstant.get(in.nextString());
    }

    @Override
    public void write(JsonWriter out, E value) throws IOException {
        out.value(value == null ? null : constantToValue.get(value));
    }
}
